<?php
class kernel{
	var $db, $tm;
	
	function execute($file){
		is_file($file) or ht_error404();
		
		$db = $this->db;
		$tm = $this->tm;
		$ht = $this->filter();
		
		// assign
		$tm->assign('ht', $ht);
		$tm->assign('webext', _WEBEXT);
		$tm->assign('webdir', _WEBDIR);
		$tm->assign('sitedir', ht_sitedir());
		$tm->assign('skindir', ht_sitedir() . $tm->themedir(false));

		// require
		require($file);
	}
	
	function routing($pinfo){
		$purl = explode('/', $pinfo);
		if(empty($purl)) ht_error404();
		
		// node
		$node = array();
		foreach($purl as $val){
			if(is_numeric($val)) continue;
			if(trim($val) !='' ){
				$node[] = $val;
			}
		}
		if(empty($node)) ht_error404();

		// file
		$rdir = ROOTDIR .'/routers/';
		$file = $rdir .'err404.ctl.php';
		if(is_dir($rdir . $node[0])) $rdir .= $node[0] .'/';
		while(!empty($node)){
			$file = $rdir . implode('_', $node) .'.ctl.php';
			if(is_file($file)) break;
			array_pop($node);
		}
		
		// exec
		$this->execute($file);
	}
	
	function filter(){
		$rules = array(); $qstrs = array();
		$filter = @$GLOBALS['config']['filter'];
		foreach($filter as $rule => $qstr){
			$rules[] = '/^\/'. $rule .'$/';
			$qstrs[] = $qstr;
		}
		
		$pinfo = $_SERVER['PATH_INFO'];
		$pinfo = preg_replace($rules, $qstrs, $pinfo, 1);
		if(strstr($pinfo, '/')) ht_error404();
		parse_str($pinfo, $pstrs);
		return $pstrs;
	}
	
	function tmname(){
		$theme = @$GLOBALS['config']['theme'];
		if(!is_array($theme)) return 'default';
		
		$pinfo = strtolower($_SERVER['PATH_INFO']);
		$route = explode('/', $pinfo);
		if(empty($route)) ht_error404();

		if(isset($theme[@$route[1]])){
			return strtolower($theme[@$route[1]]);
		}else{
			return strtolower(@$theme['*']);
		}
	}
	
	function __construct(){
		defined('ROOTDIR') or die('Undefined ROOTDIR!');
		defined('HTMLEXT') or die('Undefined HTMLEXT!');

		// pathinfo
		$pinfo = @$_SERVER['PATH_INFO'];
		if(!REWRITE && substr($pinfo, -1)=='/'){
			$_SERVER['PATH_INFO'] = substr($pinfo, 0, -1);
			$pinfo = $_SERVER['PATH_INFO'];
		}
		if($pinfo=='') $_SERVER['PATH_INFO'] = '/index';
		$pinfo = strtolower($_SERVER['PATH_INFO']);
		
		// init theme
		$this->tm = new theme($pinfo);
		$this->tm->name = $this->tmname();

		// rewrite
		if(REWRITE){
			define('_WEBEXT', HTMLEXT);
			define('_WEBDIR', ht_sitedir());
		}else{
			define('_WEBEXT', '');
			define('_WEBDIR', $_SERVER['SCRIPT_NAME'] .'/');
		}
		
		// init dbase
		$this->db = new dbase();
		$GLOBALS['db'] = &$this->db;
		
		// routing
		$this->routing($pinfo);
	}
	
	function __destruct(){
		unset($this->db, $this->tm);
	}
}
?>